package entity

import (
	"errors"
	"fmt"
	"net/http"
	"os"
	"time"

	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/workflow"
	"shqsoft.cn/pasnj/workflow/entity"

	"github.com/jinzhu/gorm"
	"github.com/labstack/echo"
)

//SJXQ 数据需求
type SJXQ struct {
	ID       int     `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	YWTX     string  `gorm:"column:YWTX"`
	XQJS     string  `gorm:"column:XQJS"`
	EMNM     string  `gorm:"column:EMNM"`
	LXR      string  `gorm:"column:LXR"`
	LXRDH    string  `gorm:"column:LXRDH"`
	UID      int     `gorm:"column:UID"`
	FID      int     `gorm:"column:FID"`
	FRID     int     `gorm:"column:FRID"`
	Progress float64 `gorm:"-" json:"progress"`
	StepName string  `gorm:"-" json:"stepName"`
	Status   string  `gorm:"-" json:"status"`
	STEP     int     `gorm:"-" json:"step"`

	CREATETIME time.Time `gorm:"column:CREATETIME"`
	UPDATETIME time.Time `gorm:"column:UPDATETIME"`
}

//TableName User用户表名
func (SJXQ) TableName() string {
	return "T_CONF_SJXQ"
}

//BeforeSave 保存前的触发器
func (i *SJXQ) BeforeSave(tx *gorm.DB) (err error) {
	// var count int
	// sqlEx := "SELECT COUNT(*) count FROM DIM_USER WHERE PDID IN(24,8,9,125,25,30,23,75,76,53,32,31,116,81) AND STATUS=1 AND EMID=?"
	// row := tx.Raw(sqlEx, i.UID).Row()
	// row.Scan(&count)
	// if count <= 0 {
	// 	return fmt.Errorf("您无权限提交，请联系系统管理员。")
	// }
	if i.FID == 0 {
		return errors.New("未上传附件或上传附件不正确，请删除后重新上传")
	}
	if i.ID > 0 {
		row := base.DB.Model(SJXQ{}).Where("ID=?", i.ID).Select("FRID").Row()
		row.Scan(&i.FRID)
	}
	if i.FRID == 0 {
		runid, err := workflow.Create(5, i.UID, tx)
		if err != nil {
			return err
		}
		i.FRID = runid
	}
	i.CREATETIME = time.Now()
	i.UPDATETIME = time.Now()
	sqlEx := "select SysUserName from T_SysUser where ID=?"
	row := tx.Raw(sqlEx, i.UID).Row()
	row.Scan(&i.EMNM)
	return
}
func (i *SJXQ) AfterDelete(tx *gorm.DB) (err error) {
	//删除所有附件
	if i.FID > 0 {
		var fj BaseFJ
		err = base.DB.First(&fj, i.FID).Error
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
		fileName := fj.FJMC + "." + fj.FJLX

		path, err := base.WorkDir()
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
		filePath := path + "/upload_file/doc/" + fileName

		err = os.Remove(filePath)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
		err = base.DB.Where([]int{i.FID}).Delete(BaseFJ{}).Error
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	if i.FRID > 0 {
		return workflow.DeleteWithTx(i.FRID, tx)
	}
	return nil
}

//AfterFind 查询后触发器
func (i *SJXQ) AfterFind(tx *gorm.DB) (err error) {

	if i.FRID == 0 {
		i.Status = "exception"
		i.StepName = "校验错误"
		return
	}
	run := entity.FlowRun{}
	if err = tx.Find(&run, i.FRID).Error; err != nil {
		tx.Rollback()
		return
	}
	wf := workflow.GetWorkFlow(run.WFID)
	if wf == nil {
		return fmt.Errorf("指定的流程ID:%d在流程配置中不存在！", run.WFID)
	}
	act := wf.GetAction(run.Step)
	if act == nil {
		return fmt.Errorf("指定的stepID:%d在流程%s配置中不存在！", run.Step, wf.Name)
	}
	count := len(wf.Actions)
	i.STEP = run.Step
	i.StepName = "审批中"
	if i.STEP == 1 {
		i.StepName = "申请中"
	}
	i.Progress = float64(act.Step*100) / float64(count)
	if i.Progress >= 100 && run.State == "0" {
		i.Progress = 95
	}
	i.Status = ""
	if run.State == "0" {
		i.Status = "active"
	} else if run.State == "2" {
		i.StepName = "已中止"
		i.Status = "exception"
	} else {
		i.StepName = "已完成"
		i.Status = "success"
	}
	return
}

func SJXQEF() base.EntityFunc {
	return func() interface{} {
		entity := SJXQ{}
		return &entity
	}
}
func SJXQESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []SJXQ
		return &entities
	}
}

func init() {
	dao := base.NewDefaultDao(SJXQEF(), SJXQESF(), nil)
	filter := base.WorkFolowFilter{
		FilterColName: "FRID",
	}
	filter.SetAdditional("wfid", "5")
	dao.Fileter = &filter
	base.DaoPoolObj.Put("SJXQ", dao)
}
